import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class AddSubscriber1 extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
	{
		doPost(request,response);
	}//doGet

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
	{
		RequestDispatcher dispatcher = null;
		String event = request.getParameter("eventAction");
		if( event.equals("exit") )
		{
			dispatcher = request.getRequestDispatcher("/jsp/OperatorActivities.jsp");
			dispatcher.forward(request,response);
		}
		try
		{
			String msg = "";
			String jspUrl = "";
			String subname = request.getParameter("subname");
			String mobno = request.getParameter("mobno");
			String simId = request.getParameter("simid");
			String address = request.getParameter("address");
			int docid = Integer.parseInt(request.getParameter("doctype"));
			Collection vector = new Vector();

			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airtel","root","root");
			Statement stmt = con.createStatement();

			int id = 0;
			ResultSet rs = stmt.executeQuery("select max(id) from subscriber");
			if(rs.next())
			{
				if( rs.getString(1) != null )
				{
					id = Integer.parseInt(rs.getString(1));
				}
			}
			id++;

			rs.close();
			rs = stmt.executeQuery("select mobile from subscriber where mobile='"+mobno+"'");
			if( rs.next() == false )
			{
				stmt.executeUpdate("insert into subscriber values('"+id+"','"+subname+"','"+mobno+"','"+simId+"','"+address+"','"+docid+"')");
				msg = "New Subscriber Added with Name: "+subname+" and Number: "+mobno ;
				Collection vectorr = new Vector();
				ResultSet rss = stmt.executeQuery("select id,name from outletdetails");
				while(rss.next())
				{
					vectorr.add(rss.getString(1));
					vectorr.add(rss.getString(2));
				}   
				request.setAttribute("outletnames",vectorr);
				jspUrl = "/jsp/SimActivation.jsp";
			}
			else
			{
				rs = stmt.executeQuery("select * from documents");
				while(rs.next())
				{
					vector.add(rs.getString(1));
					vector.add(rs.getString(2));
				}   
				request.setAttribute("documents",vector);
				msg = "Already existed with  "+subname;
				jspUrl = "/jsp/Subscriber.jsp";
			}

			request.setAttribute("msg",msg);
			dispatcher = request.getRequestDispatcher(jspUrl);
			dispatcher.forward(request,response);
		}//try
		catch(Exception e)
		{
            e.printStackTrace();
		}//catch
	}//doPost
}//class